<?php
class LoginController extends AppController {
	var $name = 'Login';
	var $components = array('Menu','Init');
	var $uses = array('Member', 'Setting');

	function beforeFilter() {
		$this->Init->startup($this);
		$this->Init->init();
		$this->Init->getKeyword();
		$_session = $this -> Session -> read();
		$this->loadModel('Hitcounter');
		$row = $this->Hitcounter->get(session_id());
		if ($row == 0) {
			$data = array(
				"session_id" => session_id(),
				"ref_url" => env("REQUEST_URI"),
				"ip_address" => env("REMOTE_ADDR"),
				"activity" => date("Y-m-d H:i:s")
			);
			$this->Hitcounter->save($data);
		}
		$_menus = $this->Menu->getMenu($this->params['controller'],$this->params['action']);
		for ($i = 1; $i <=6; $i++) {
			if ($_menus[$i-1] == 1) {
				$this->set('current'.$i,'class="current"');
			}
			else {
				$this->set('current'.$i,'');
			}
		}
                $this->set('activeNav', 'Home');
    }

	/**
	 * Enter description here ...
	 */
	function index($refer = null) {
		$this->layout = 'inside';

		if (!$this->Session->read("lang")) {
			$lang = "vie";
		} else {
			$lang = $this->Session->read("lang");
		}
		$login = $this->Session->read('User.login');

		if (!empty($login)) {
			$this->redirect(array('controller'=>'member'));
		}

		Configure::write("Config.language", $lang);
		$this->set('lang',$lang);

 		if(!empty($this->data)) {
 			$user = trim($this->data['Login']['username']);
 			$pass = Security::hash(trim($this->data['Login']['password']), null, true);

 			$member = $this->Member->find(
 				'first',
 				array('conditions'		=> array(
 					'Member.username'	=> $user,
 					'Member.passwd'		=> $pass
 				))
 			);

 			if(!empty($member)) {
 				unset($member['Member']['passwd']);
 				$login['Member'] = $member['Member'];

				// discount vip
				$product_discount_for_vip = $this->Setting->getVipDiscount();
 				$this->Session->write('User.login', $login['Member']);
                                $this->Session->write('discount_for_vip', $product_discount_for_vip['Setting']['value']);
				if (isset($refer) && $refer == 'order') {
					$this->redirect(array('controller'=>'order','action' => 'index'));
				}
				else {
					$this->redirect(array('controller'=>'member','action' => 'index'));
				}
 			} else {
 				$this->Session->setFlash(__('Invalid Username or Password.', true));
 			}

 		}

	}

	/**
	 * Enter description here ...
	 */
	function check_user() {
		$this->layout = null;

		$validateValue = $_POST['validateValue'];
		$validateId = $_POST['validateId'];
		$validateError = $_POST['validateError'];

		$this->loadModel('Member');
		$one = $this->Member->find('first', array('conditions'=>array('Username'=>$validateValue)));
		if(!empty($one)) {
			$error = array(
				0 => $validateId,
				1 => $validateError,
				2 => 'false'
			);
		} else {
			$error = array(
				0 => $validateId,
				1 => $validateError,
				2 => 'true'
			);
		}
		$this->set('error', $error);
	}

	/**
	 * Enter description here ...
	 */
	function check_email() {
		$this->layout = null;

		$validateValue = $_POST['validateValue'];
		$validateId = $_POST['validateId'];
		$validateError = $_POST['validateError'];

		$this->loadModel('Member');
		$one = $this->Member->find('first', array('conditions'=>array('Email'=>$validateValue)));
		if(!empty($one)) {
			$error = array(
				0 => $validateId,
				1 => $validateError,
				2 => 'false'
			);
		} else {
			$error = array(
				0 => $validateId,
				1 => $validateError,
				2 => 'true'
			);
		}
		$this->set('error', $error);
	}

	function logout() {
            $this->Session->delete('User.login');
            $this->Session->delete('User.order');
            $this->Session->delete('discount_for_vip');
            $this->redirect('/');
	}

	function forgot_pwd(){

            $this->layout = 'inside';

            App::import('Component', 'Captcha');
            $captcha = new CaptchaComponent();
            $captcha->startup($this);
            $this->set('captcha_image_url', Router::url(array('controller'=>'captcha', 'action'=>'securimage'))); //url for the captcha image
            $captcha_error_msg = __('The code you entered does not match', true);

            if (isset($this->data)) {
                if( $this->captcha->check($this->data['Security']['code']) == false ) {
                    $this->set('error_captcha', $captcha_error_msg); //set error msg
                    //$this->render(); //reload page
                            } else {
                                    $this->loadModel('Member');
                                    // kiem tra su ton tai cua email
                                    $_check = $this->Member->find('first', array(
                                            'conditions' => array(
                                                    'username' => $this->data['Member']['username']
                                            )
                                    ));

                                    if (!empty($_check)) {
                                            //if(ACTIVE_REGISTER) {
                                                    if(MAIL_SMTP) {
                                                            $this->Email->smtpOptions = array(
                                                            'port'		=> MAIL_PORT,
                                                            'timeout'	=> '30',
                                                            'host'		=> MAIL_HOST,
                                                            'username'	=> MAIL_USER,
                                                            'password'	=> MAIL_PASSWD,
                                                            );
                                                            $this->Email->delivery = 'smtp';
                                                    }

                                                    $this->Email->from = MAIL_CONTACT ;
                                                    $this->Email->to = $_check['Member']['email'];
                                                    $this->Email->subject = __('Cấp lại mật khẩu mới cho tài khoản ở Vipecom.vn', true);
                                                    $this->Email->template = 'forgot_pwd';
                                                    $this->Email->sendAs = 'html';

                                                    $mail = array(
                                                            'username'  => $_check ['Member']['username'],
                                                            'token'		=> $_check ['Member']['token'],
                                                            'id'		=> $_check ['Member']['id'],
                                                            'name'      => $_check ['Member']['fullName']
                                                    );
                                                    $this->set('mail', $mail);

                                                    if($this->Email->send()) {
                                                            $this->Session->setFlash(__('New password is sent your email.', true));
                                                    } else {
                                                            $this->Session->setFlash(__('Mail function error. Please contact administrator.', true));
                                                    }
                                                    $this->redirect(array('controller' => 'login', 'action' => 'forget_pwd'));

                            }
                            else {
                                    $this->Session->setFlash(__('Username does not exist in system ', true));
                                    $this->redirect(array('controller' => 'login', 'action' => 'forget_pwd'));
                }
                }
            }
	}

	function forgot_pwd_complete($url) {
		// doi password ngau nhien
		// kiem tra hop le
		$this->layout = 'content';
		$this->loadModel('Member');

		list($id,$token) = explode("-", $url);

		$this->set('id',$id);
		$this->set('token',$token);

		$_check = $this->Member->find('first', array(
			'conditions' => array(
				'Member.id'    =>  $id,
				'Member.token' =>   $token
			)
		));

		if (empty($_check)) {
			$this->redirect('/');
		}

		if(!empty($this->data)) {
			$this->Member->save(array(
				'passwd'	=> Security::hash($this->data['Member']['ipasswd'], null, true),
				'id'		=> $id
			));

			$this->Session->setFlash(__('Password is changed.', true));

			$this->redirect(array('controller'=>'login', 'action' => 'index'));
		}

	}
}
?>